package com.aixingfu.sports.ui.activity;

import android.content.Context;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.AbsListView;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.aixingfu.sports.ElectronicContractActivity;
import com.aixingfu.sports.MVP.contract.CacheChargeClassParamContract;
import com.aixingfu.sports.MVP.contract.PersonalTrainContract;
import com.aixingfu.sports.MVP.contract.RetrievePwdContract;
import com.aixingfu.sports.MVP.contract.SaleContract;
import com.aixingfu.sports.MVP.presenter.CacheChargeClassParamPresenter;
import com.aixingfu.sports.MVP.presenter.PersonalTrainPresenter;
import com.aixingfu.sports.MVP.presenter.RetrievePwdPresenter;
import com.aixingfu.sports.MVP.presenter.SalePresenter;
import com.aixingfu.sports.Model.CacheChargeClassParamModel;
import com.aixingfu.sports.Model.CodeModel;
import com.aixingfu.sports.Model.PersonalTrainModel;
import com.aixingfu.sports.Model.RetrievePwdModel;
import com.aixingfu.sports.Model.SaleModel;
import com.aixingfu.sports.R;
import com.aixingfu.sports.bean.MessageEventPrivateEducation;
import com.aixingfu.sports.view.PopChargeCoacheCheckChooseID;
import com.aixingfu.sports.view.PopChargeSourceCheckChooseID;
import com.aixingfu.sports.view.PopSaleCheckChooseID;
import com.aixingfu.sports.view.PopupWindowCheckChoose;
import com.alibaba.android.arouter.facade.annotation.Route;
import com.alibaba.android.arouter.launcher.ARouter;
import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.bumptech.glide.request.RequestOptions;
import com.orie.librarybase.base.BaseActivity;
import com.orie.librarybase.utils.CountDownTimerUtils;
import com.orie.librarybase.utils.MoneyEditUtils;
import com.orie.librarybase.utils.UserUtils;
import com.vondear.rxtool.view.RxToast;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import de.hdodenhof.circleimageview.CircleImageView;
//购买私教课
@Route(path = "/main/BuyingPrivateCoursesActivity")
public class BuyingPrivateCoursesActivity extends BaseActivity implements SaleContract.MyView, CacheChargeClassParamContract.MyView, PersonalTrainContract.MyView, RetrievePwdContract.MyView {

    @BindView(R.id.iv_back)
    ImageView ivBack;
    @BindView(R.id.tv_title)
    TextView tvTitle;
    @BindView(R.id.tv_name)
    TextView tvName;
    @BindView(R.id.tv_sex)
    TextView tvSex;
    @BindView(R.id.tv_card_type)
    TextView tvCardType;
    @BindView(R.id.tv_phone)
    TextView tvPhone;
    @BindView(R.id.tv_card_code)
    TextView tvCardCode;
    @BindView(R.id.tv_product)
    TextView tvProduct;
    @BindView(R.id.ll_product)
    LinearLayout llProduct;

    @BindView(R.id.tv_coach)
    TextView tvCoach;
    @BindView(R.id.ll_coach)
    LinearLayout llCoach;
    @BindView(R.id.tv_discount)
    TextView tvDiscount;
    @BindView(R.id.ll_discount)
    LinearLayout llDiscount;
    @BindView(R.id.tv_gift)
    TextView tvGift;
    @BindView(R.id.ll_gift)
    LinearLayout llGift;
    @BindView(R.id.ed_original_amount)
    EditText edOriginalAmount;
    @BindView(R.id.ed_total_sum)
    EditText edTotalSum;
    @BindView(R.id.tv_channel)
    TextView tvChannel;
    @BindView(R.id.ed_remarks)
    EditText edRemarks;
    @BindView(R.id.tv_back)
    TextView tvBack;
    @BindView(R.id.tv_next)
    TextView tvNext;
    @BindView(R.id.ed_number)
    EditText edNumber;
    @BindView(R.id.ll_channel)
    LinearLayout llChannel;
    @BindView(R.id.tv_birthday)
    TextView tvBirthday;
    @BindView(R.id.iv_head)
    CircleImageView ivHead;
    @BindView(R.id.ed_phone)
    EditText edPhone;
    @BindView(R.id.tv_getcode)
    TextView tvGetcode;
    @BindView(R.id.ed_code)
    EditText edCode;
    private String member_id;
    private String productId;
    private String course_num;
    private String coachId = "", channelId = "";
    private SalePresenter salePresenter;
    private List<SaleModel.DataBean> saleList;
    private PopSaleCheckChooseID popSaleCheckChooseID;
    private String sale_id = "";
    private ArrayList<String> mList = new ArrayList();
    private PopupWindowCheckChoose mPopup;
    private CacheChargeClassParamPresenter cacheChargeClassParamPresenter;
    private PersonalTrainPresenter personalTrainPresenter;
    private String mnumber;
    private String mgift;
    private String totalSum;
    private String remarks;
    private List<PersonalTrainModel.DataBean.ChargeCoacheListBean> charge_coache_list;
    private List<PersonalTrainModel.DataBean.ChargeSourceBean> charge_source;
    private PopChargeCoacheCheckChooseID popChargeCoacheCheckChooseID;
    private PopChargeSourceCheckChooseID popChargeSourceCheckChooseID;
    private String mChannel = "";
    private String mobile = "";
    private RetrievePwdPresenter retrievePwdPresenter;
    private String codedata;
    private CountDownTimerUtils countDownTimerUtils;


    @Override
    protected int provideContentViewId() {
        return R.layout.activity_buying_private_courses;
    }

    public static void startActivityByRoute() {
        ARouter.getInstance().build("/main/BuyingPrivateCoursesActivity").navigation();
    }

    @Override
    protected void initView(Bundle savedInstanceState) {
        ButterKnife.bind(this);
        try {
            if (!EventBus.getDefault().isRegistered(this)) {//加上判断
                EventBus.getDefault().register(this);
            }
            tvTitle.setText("购买私教课");
            Bundle bundle = getIntent().getExtras();
            member_id = bundle.getString("member_id", "");
            mobile = bundle.getString("mobile", "");
            salePresenter = new SalePresenter();
            salePresenter.attachView(this);
            cacheChargeClassParamPresenter = new CacheChargeClassParamPresenter();
            cacheChargeClassParamPresenter.attachView(this);
            personalTrainPresenter = new PersonalTrainPresenter();
            personalTrainPresenter.attachView(this);
            retrievePwdPresenter = new RetrievePwdPresenter();
            retrievePwdPresenter.attachView(this);
            getPrivateEducation();
            getSale();
            mList = getPopList();
            mPopup = new PopupWindowCheckChoose(BuyingPrivateCoursesActivity.this, mList);
            mPopup.setTagTxt("请选择")//设置顶部title的内容
                    .setButtomTxt("取消")//设置底部按钮内容
                    .setChoiceMode(AbsListView.CHOICE_MODE_SINGLE);//单选
            //单选
            mPopup.setOnEventLisenter(positionList -> {
                mPopup.dismiss();
                tvGift.setText(mList.get(positionList.get(0)));
            });
            MoneyEditUtils.afterDotTwo(edTotalSum);
            edPhone.setText(mobile);
            edPhone.setEnabled(false);
        }catch (Exception e){
            e.printStackTrace();
        }

    }

    /**
     * 数据
     *
     * @return
     */
    public ArrayList<String> getPopList() {
        ArrayList<String> popList = new ArrayList<>();
        popList.add("领取");
        popList.add("未领取");
        return popList;
    }

    public void getPrivateEducation() {
        if (personalTrainPresenter.isViewAttached()) {
            HashMap<String, String> map = new HashMap<>();
            map.put("member_id", member_id);
            personalTrainPresenter.getPersonalTrain(map);
        }
    }

    public void getSale() {
        if (salePresenter.isViewAttached()) {
            HashMap<String, String> map = new HashMap<>();
            map.put("venue_id", UserUtils.getUserId(BuyingPrivateCoursesActivity.this));
            salePresenter.getSale(map);
        }
    }

    public void getCode(String accountNumber) {
        if (retrievePwdPresenter.isViewAttached()) {
            String companyID = UserUtils.getCompanyID(BuyingPrivateCoursesActivity.this);
            HashMap<String, String> map = new HashMap<>();
            map.put("mobile", accountNumber);
            map.put("company_id", companyID);
            map.put("type", "member");
            retrievePwdPresenter.getCode(map);
        }
    }


    public void getCacheChargeClassParam(String code) {
        if (cacheChargeClassParamPresenter.isViewAttached()) {
            HashMap<String, String> map = new HashMap<>();
            map.put("member_id", member_id);
            map.put("charge_class_id", productId);
            map.put("course_amount", mnumber);
            if ("领取".equals(mgift)) {
                map.put("gift_status", "1");
            } else if ("未领取".equals(mgift)) {
                map.put("gift_status", "2");
            }
            map.put("total_price", totalSum);
            map.put("note", remarks);
            if (!TextUtils.isEmpty(course_num)) {
                if (Integer.parseInt(course_num) == 1) {
                    map.put("product_type", "alone");
                } else if (Integer.parseInt(course_num) > 1) {
                    map.put("product_type", "many");
                }
            }
            map.put("sale_type", channelId);
            map.put("sale_id", sale_id);
            map.put("coach_id", coachId);
            map.put("mobile", mobile);
            map.put("code", code);
//            map.put("discount_note", "");
            cacheChargeClassParamPresenter.getCacheChargeClassParam(map);
        }
    }

    @Override
    protected void initEvent() {
    }

    @Override
    protected void beforeInit() {
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // TODO: add setContentView(...) invocation
        ButterKnife.bind(this);
    }

    @OnClick({R.id.iv_back, R.id.ll_product, R.id.ll_coach, R.id.ll_discount, R.id.ll_gift, R.id.ll_channel, R.id.tv_back, R.id.tv_next, R.id.tv_getcode})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.iv_back:
                hideIputKeyboard();
                finish();
                break;
            case R.id.ll_product:
                hideIputKeyboard();
                ARouter.getInstance().build("/main/PrivateEducationActivity").withString("member_id", member_id).navigation();
                break;
            case R.id.ll_coach:
                hideIputKeyboard();
                if (popChargeCoacheCheckChooseID != null) {
                    popChargeCoacheCheckChooseID.showPop(tvCoach);
                }
                break;
            case R.id.ll_discount:
                hideIputKeyboard();
                if (popSaleCheckChooseID != null) {
                    popSaleCheckChooseID.showPop(tvDiscount);
                }
                break;
            case R.id.ll_gift:
                hideIputKeyboard();
                if (mPopup != null) {
                    mPopup.showPop(tvGift);
                }
                break;
            case R.id.ll_channel:
                hideIputKeyboard();
                if (popChargeSourceCheckChooseID != null) {
                    popChargeSourceCheckChooseID.showPop(tvChannel);
                }

                break;
            case R.id.tv_back:
                hideIputKeyboard();
                finish();
                break;
            case R.id.tv_next:
                String produce = tvProduct.getText().toString();
                mnumber = edNumber.getText().toString();
                mgift = tvGift.getText().toString();
                totalSum = edTotalSum.getText().toString();
                remarks = edRemarks.getText().toString();
                mChannel = tvChannel.getText().toString();
                String mobile = edPhone.getText().toString();
                String code = edCode.getText().toString();
                if (TextUtils.isEmpty(produce)) {
                    RxToast.normal(BuyingPrivateCoursesActivity.this, "请选择私教产品").show();
                } else if (TextUtils.isEmpty(mnumber)) {
                    RxToast.normal(BuyingPrivateCoursesActivity.this, "请输入购买数量").show();
                } else if (TextUtils.isEmpty(mgift)) {
                    RxToast.normal(BuyingPrivateCoursesActivity.this, "是否领取赠品").show();
                } else if (TextUtils.isEmpty(totalSum) || "0".equals(totalSum)) {
                    RxToast.normal(BuyingPrivateCoursesActivity.this, "请输入总金额").show();
                } else if (TextUtils.isEmpty(mChannel)) {
                    RxToast.normal(BuyingPrivateCoursesActivity.this, "请选择私教渠道").show();
                } else if (TextUtils.isEmpty(code)) {
                    RxToast.normal(BuyingPrivateCoursesActivity.this, "请输入验证码").show();
                } else{
                    getCacheChargeClassParam(code);
                }
                break;
            case R.id.tv_getcode:
                String phone = edPhone.getText().toString();
                if (TextUtils.isEmpty(phone)){
                    RxToast.normal(BuyingPrivateCoursesActivity.this,"请输入手机号").show();
                }else {
                    countDownTimerUtils = new CountDownTimerUtils(BuyingPrivateCoursesActivity.this, tvGetcode, 60000, 1000);
                    countDownTimerUtils.start();
                    getCode(phone);
                }
                break;
        }
    }
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEvent(MessageEventPrivateEducation event) {
        tvProduct.setText(event.getName());
        productId = event.getId();
        course_num = event.getCourse_num();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        // 注销订阅者
        EventBus.getDefault().unregister(this);
    }

    @Override
    public void showToast(String msg, String state) {

    }

    @Override
    public void setCode(CodeModel data) {
        if (data.getCode() == 1) {
            codedata = String.valueOf(data.getData());
            RxToast.normal(BuyingPrivateCoursesActivity.this, data.getMessage()).show();
//            edCode.setText(codedata);
        } else {
            RxToast.normal(BuyingPrivateCoursesActivity.this, data.getMessage()).show();
        }
    }

    @Override
    public void setRetievePwd(RetrievePwdModel data) {

    }

    @Override
    public void setPersonalTrain(PersonalTrainModel data) {
        if (data.getCode() == 1) {
            PersonalTrainModel.DataBean.MemberInfoBean member_info = data.getData().getMember_info();
            tvName.setText("会员姓名：" + member_info.getUsername());
            tvPhone.setText("手机号：" + member_info.getMobile());
            String sex = member_info.getSex();
            if ("1".equals(sex)) {
                tvSex.setText("性别：" + "男");
            } else if ("2".equals(sex)) {
                tvSex.setText("性别：" + "女");
            }
            tvBirthday.setText("会员生日：" + member_info.getBirth_date());
            tvCardCode.setText("证件号码：" + member_info.getMember_id_card());
            String member_id_card_type = member_info.getMember_id_card_type();
            if ("1".equals(member_id_card_type)) {
                tvCardType.setText("证件类型：" + "身份证");
            } else if ("2".equals(member_id_card_type)) {
                tvCardType.setText("证件类型：" + "居住证");
            } else if ("3".equals(member_id_card_type)) {
                tvCardType.setText("证件类型：" + "签证");
            } else if ("4".equals(member_id_card_type)) {
                tvCardType.setText("证件类型：" + "护照");
            } else if ("5".equals(member_id_card_type)) {
                tvCardType.setText("证件类型：" + "户口本");
            } else if ("6".equals(member_id_card_type)) {
                tvCardType.setText("证件类型：" + "军人证");
            }
            charge_coache_list = data.getData().getCharge_coache_list();
            charge_source = data.getData().getCharge_source();
            popChargeCoacheCheckChooseID = new PopChargeCoacheCheckChooseID(BuyingPrivateCoursesActivity.this, charge_coache_list);
            popChargeCoacheCheckChooseID.setTagTxt("请选择销售教练")//设置顶部title的内容
                    .setButtomTxt("取消")//设置底部按钮内容
                    .setChoiceMode(AbsListView.CHOICE_MODE_SINGLE);//单选
            //单选
            popChargeCoacheCheckChooseID.setOnEventLisenter(positionList -> {
                popChargeCoacheCheckChooseID.dismiss();
                tvCoach.setText(charge_coache_list.get(positionList.get(0)).getName());
                coachId = charge_coache_list.get(positionList.get(0)).getId();
            });

            popChargeSourceCheckChooseID = new PopChargeSourceCheckChooseID(BuyingPrivateCoursesActivity.this, charge_source);
            popChargeSourceCheckChooseID.setTagTxt("请选择私教渠道")//设置顶部title的内容
                    .setButtomTxt("取消")//设置底部按钮内容
                    .setChoiceMode(AbsListView.CHOICE_MODE_SINGLE);//单选
            //单选
            popChargeSourceCheckChooseID.setOnEventLisenter(positionList -> {
                popChargeSourceCheckChooseID.dismiss();
                tvChannel.setText(charge_source.get(positionList.get(0)).getValue());
                channelId = charge_source.get(positionList.get(0)).getId();
            });
        }
        RequestOptions options = new RequestOptions()
                .centerCrop()
                .dontAnimate()
                .placeholder(R.mipmap.touxiang)
                .diskCacheStrategy(DiskCacheStrategy.ALL);
        Glide.with(BuyingPrivateCoursesActivity.this)
                .load(data.getData().getMember_info().getAvatar_url())
                .apply(options)
                .into(ivHead);
    }

    @Override
    public void setCacheChargeClassParam(CacheChargeClassParamModel data) {
        if (data.getCode() == 1) {
            ARouter.getInstance().build("/main/PaymentClassActivity").withString("member_id", data.getData().getMember_id()).navigation();
            RxToast.normal(BuyingPrivateCoursesActivity.this, data.getMessage()).show();
        } else {
            RxToast.normal(BuyingPrivateCoursesActivity.this, data.getMessage()).show();
        }
    }

    @Override
    public void setSale(SaleModel data) {
        if (data.getCode() == 1) {
            saleList = data.getData();
            popSaleCheckChooseID = new PopSaleCheckChooseID(BuyingPrivateCoursesActivity.this, saleList);
            popSaleCheckChooseID.setTagTxt("请选择会籍")//设置顶部title的内容
                    .setButtomTxt("取消")//设置底部按钮内容
                    .setChoiceMode(AbsListView.CHOICE_MODE_SINGLE);//单选
            //单选
            popSaleCheckChooseID.setOnEventLisenter(positionList -> {
                popSaleCheckChooseID.dismiss();
                tvDiscount.setText(saleList.get(positionList.get(0)).getName());
                sale_id = saleList.get(positionList.get(0)).getSale_id();
            });
        }
    }

    @Override
    public void showLoading() {
        showLoadingDialog();
    }

    @Override
    public void hideLoading() {
        dismissLoadingDialog();
    }

    @Override
    public Context getMyContext() {
        return this;
    }

    //关闭软键盘
    public void hideIputKeyboard() {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                InputMethodManager mInputKeyBoard = (InputMethodManager) getSystemService(INPUT_METHOD_SERVICE);
                if (getCurrentFocus() != null) {
                    mInputKeyBoard.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(),
                            InputMethodManager.HIDE_NOT_ALWAYS);
                    getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN);
                }
            }
        });
    }
}
